import React from "react";
import { View, Text, Button, FlatList, Pressable, StyleSheet, Animated } from "react-native";
import CartItem from "./CartItem";

// 定义Cart组件，接收购物车商品数组、添加商品、移除商品以及清空购物车的操作作为props
const Cart = ({ cartItems, onAdd, onRemove, onClearCart }) => {
  // 计算购物车中所有商品的总价
  const totalPrice = cartItems.reduce(
    (total, item) => total + item.price * item.quantity,
    0
  );

  // 初始化一个动画值
  const scaleAnim = new Animated.Value(1);

  // 定义按钮按下时的动画效果，使按钮轻微缩小
  const onPressInAnimation = () => {
    Animated.spring(scaleAnim, {
      toValue: 0.95,
      useNativeDriver: true,
    }).start();
  };

  // 定义按钮释放时的动画效果，使按钮恢复原状
  const onPressOutAnimation = () => {
    Animated.spring(scaleAnim, {
      toValue: 1,
      friction: 3,
      tension: 100,
      useNativeDriver: true,
    }).start();
  };

  // 组件的渲染部分
  return (
    <View style={styles.container}>
      {/* 使用FlatList展示购物车商品列表 */}
      <FlatList
        data={cartItems}
        keyExtractor={(item) => item.id.toString()} // 定义每个列表项的key
        renderItem={({ item }) => ( // 渲染每个购物车项
          <CartItem
            id={item.id}
            name={item.name}
            price={item.price}
            quantity={item.quantity}
            onAdd={() => onAdd(item)}
            onRemove={() => onRemove(item)}
          />
        )}
      />
      {/* 显示总价 */}
      <Text>总价: ￥{totalPrice.toFixed(2)}</Text>
      {/* 结算和清空购物车按钮，使用动画效果 */}
      <View style={styles.buttonsContainer}>
        {/* 结算购物车按钮 */}
        <Animated.View style={[styles.button, { transform: [{ scale: scaleAnim }] }]}>
          <Pressable onPressIn={onPressInAnimation} onPressOut={onPressOutAnimation} onPress={onClearCart}>
            <Text style={styles.buttonText}>结算购物车</Text>
          </Pressable>
        </Animated.View>
        {/* 清空购物车按钮 */}
        <Animated.View style={[styles.button, { transform: [{ scale: scaleAnim }] }]}>
          <Pressable onPressIn={onPressInAnimation} onPressOut={onPressOutAnimation} onPress={onClearCart}>
            <Text style={styles.buttonText}>清空购物车</Text>
          </Pressable>
        </Animated.View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  buttonsContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 20,
  },
  button: {
    backgroundColor: '#007bff',
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderRadius: 5,
    elevation: 2, // 为按钮添加阴影效果（仅 Android）
  },
  buttonText: {
    color: 'white',
    textAlign: 'center',
  },
});

export default Cart;
